﻿using Cyss.Core.Cache;
using Cyss.Core.Helper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Api
{
    /// <summary>
    /// 幂等性验证
    /// </summary>
    public class IdempotenceAttribute : Attribute, IActionFilter
    {
        private string IdempotenceId { set; get; }
        public IdempotenceAttribute()
        {

        }

        public void OnActionExecuted(ActionExecutedContext context)
        {

        }


        public async void OnActionExecuting(ActionExecutingContext context)
        {
            OperateResult OperateResult = new OperateResult();
            //获取token
            var Idempotence = context.HttpContext.Request.Headers["IdempotenceId"];

            if (Idempotence.Count <= 0)
            {
                OperateResult.CodeType=OperateResultCodeType.Idempotence;
                OperateResult.Message = "异常提交";
                context.Result = new JsonResult(OperateResult);
                return;
            }
            IdempotenceId = Idempotence[0];

            if (string.IsNullOrWhiteSpace(IdempotenceId))
            {
                OperateResult.CodeType=OperateResultCodeType.Idempotence;
                OperateResult.Message = "异常提交";
                context.Result = new JsonResult(OperateResult);
                return;
            }
            LogHelper.WriteTextLog(IdempotenceId, "2", "IdempotenceId");
            if (!await IdempotenceHelper.VerificationIdempotence(IdempotenceId))
            {
                OperateResult.CodeType=OperateResultCodeType.Idempotence;
                OperateResult.Message = "重复提交";
                context.Result = new JsonResult(OperateResult);
                return;
            }
        }

    }

    /// <summary>
    /// Api接口幂等性帮助类
    /// </summary>
    public class IdempotenceHelper
    {
        /// <summary>
        /// 验证 接口幂等token
        /// </summary>
        public static async Task<bool> VerificationIdempotence(string token)
        {
            var cacheManager = IOCEngine.Resolve<IStaticCacheManager>();
            if (cacheManager == null)
            {
                throw new Exception("请注册ICacheManager");
            }
            var isSuccess = await cacheManager.RemoveAsync(token);
            return isSuccess;
        }
    }


}
